const jsonServer = require("json-server");
const jwt = require("jsonwebtoken");
const md5 = require("md5");

const server = jsonServer.create();
const db = jsonServer.router("./db.json").db;

/**
 * POST /login
 * @tags users - 用户管理
 * @summary 登录
 * @param {post-login} request.body.required - 用户对象 - application/json
 * @return {object} 200 - success response
 */
server.post("/login", async (req, res) => {
  const { username, password } = req.body;

  const r = db
    .get("users")
    .find({ username, password: md5(password) })
    .value();
  if (!r) {
    throw new Error("wrong username or password");
  }
  res.send({
    status: 200,
    success: true,
    message: "login successful",
    data: "Bearer " + jwt.sign(r, process.env.JWT_KEY, { expiresIn: 1440 }),
  });
});

module.exports = () => server;
